package es.mgil.blog;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MensajeAdapter extends ArrayAdapter<Mensaje> {
	Context context;
	int layoutResourceId;
	List<Mensaje> list;

	public MensajeAdapter(Context context, int layoutResourceId) {
		this(context, layoutResourceId, new ArrayList<Mensaje>());
	}

	public MensajeAdapter(Context context, int layoutResourceId,
			List<Mensaje> list) {
		super(context, layoutResourceId, list);
		this.layoutResourceId = layoutResourceId;
		this.context = context;
		this.list = list;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		MensajeHolder holder = null;

		if (convertView == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			convertView = inflater.inflate(layoutResourceId, parent, false);

			holder = new MensajeHolder();
			holder.txtEmail = (TextView) convertView
					.findViewById(R.id.txtEmail);
			holder.txtTitle = (TextView) convertView
					.findViewById(R.id.txtTitle);
			holder.txtMessage = (TextView) convertView
					.findViewById(R.id.txtMessage);

			convertView.setTag(holder);
		} else {
			holder = (MensajeHolder) convertView.getTag();
		}

		Mensaje mensaje = list.get(position);
		holder.txtEmail.setText(mensaje.getEmail() + " (" + mensaje.getDate()
				+ ")");
		holder.txtTitle.setText(mensaje.getTitle());
		holder.txtMessage.setText(mensaje.getContent());
		((LinearLayout) convertView)
				.setGravity(mensaje.getOwner() ? Gravity.RIGHT : Gravity.LEFT);

		return convertView;
	}

	static class MensajeHolder {
		private TextView txtEmail;
		private TextView txtTitle;
		private TextView txtMessage;
	}
}
